package net.zeus.sample.rabbitmq.confirm;

import java.io.IOException;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;

import net.zeus.sample.rabbitmq.utils.ConnectionUtils;

/**
 * 异步确认模式
 * @author Michael
 *
 */
public class FirmSender {

	public static void main(String[] args) throws Exception{
		Connection conn = ConnectionUtils.getConnection();
		
		Channel channel = conn.createChannel();

		channel.queueDeclare(ConnectionUtils.CONFIRM_QUEUE_NAME, false, false, false, null);
		
		//选择confirm模式
		channel.confirmSelect();
		
		final SortedSet<Long> confirmset = Collections.synchronizedSortedSet(new TreeSet<Long>());
		
		channel.addConfirmListener(new ConfirmListener() {

			/**
			 * 没有问题的
			 */
			public void handleAck(long deliveryTag, boolean multiple) throws IOException {
				System.out.println("-- ack[multiple:" + multiple + "] --");
				if(multiple) {
					confirmset.headSet(deliveryTag + 1).clear();
				} else {
					confirmset.remove(deliveryTag);
				}
			}

			/**
			 * 
			 */
			public void handleNack(long deliveryTag, boolean multiple) throws IOException {
				System.out.println("-- nack[multiple:" + multiple + "] --");
				if(multiple) {
					confirmset.headSet(deliveryTag + 1).clear();
				} else {
					confirmset.remove(deliveryTag);
				}
			}
			
		});
	}

}
